<template>
  <p-card :bordered="true">
    <!-- 巡检操作（线材预制） -->
    <!-- 抽样SN明细编辑弹出框开始 -->
    <P-modal v-model="spotCheckModalVisible" title="SN明细" centered @ok="modalOk">
      <p-form-model
        ref="baseInfoData"
        :model="currentRow"
        :label-col="spotCheckLabelCol"
        :wrapper-col="spotCheckWrapperCol"
      >
        <p-form-model-item ref="key" label="key值" prop="key">
          <p-input v-model="currentRow.key" readonly />
        </p-form-model-item>
        <p-form-model-item ref="sn" label="SN" prop="sn">
          <p-input v-model="currentRow.sn" />
        </p-form-model-item>
        <p-form-model-item ref="inspectProject" label="检验项目" prop="inspectProject">
          <p-select v-model="currentRow.inspectProject" placeholder="please select your zone">
            <p-select-option
              v-for="(item,index) in inspectProjectOptions"
              :key="index"
              :value="item.value"
            >{{item.name}}</p-select-option>
          </p-select>
        </p-form-model-item>
        <p-form-model-item ref="photoUrl" label="图片" prop="photoUrl">
          <p-input type="text" placeholder="上传" readonly v-model="currentRow.photoUrl" />
        </p-form-model-item>
        <p-form-model-item ref="remark" label="备注" prop="remark">
          <p-input v-model="currentRow.remark" />
        </p-form-model-item>
      </p-form-model>
    </P-modal>
    <!-- 抽样SN明细编辑弹出框结束 -->
    <!-- 抽样SN明细新增弹出框开始 -->
    <P-modal v-model="spotCheckModalVisible2" title="SN明细" centered @ok="addModalOk">
      <p-form-model
        ref="baseInfoData2"
        :model="addRow"
        :label-col="spotCheckLabelCol"
        :wrapper-col="spotCheckWrapperCol"
      >
        <p-form-model-item ref="key" label="key值" prop="key">
          <p-input v-model="addRow.key" readonly />
        </p-form-model-item>
        <p-form-model-item ref="sn" label="SN" prop="sn">
          <p-input v-model="addRow.sn" />
        </p-form-model-item>
        <p-form-model-item ref="inspectProject" label="检验项目" prop="inspectProject">
          <p-select v-model="addRow.inspectProject" placeholder="please select your zone">
            <p-select-option
              v-for="(item,index) in inspectProjectOptions"
              :key="index"
              :value="item.value"
            >{{item.name}}</p-select-option>
          </p-select>
        </p-form-model-item>
        <p-form-model-item ref="photoUrl" label="图片" prop="photoUrl">
          <p-input type="text" placeholder="上传" readonly v-model="addRow.photoUrl" />
        </p-form-model-item>
        <p-form-model-item ref="remark" label="备注" prop="remark">
          <p-input v-model="addRow.remark" />
        </p-form-model-item>
      </p-form-model>
    </P-modal>
    <!-- 抽样SN明细新增弹出框结束 -->
    <div>
      <!-- 侧边弹出开始 -->
      <p-drawer
        title="上传图片"
        placement="right"
        :closable="true"
        :visible="drawerVisible"
        :after-visible-change="afterVisibleChange"
        width="40vw"
        @close="onClose"
      >
        <!-- <p-alert message="抽检SN明细" type="info" /> -->
        <p-table
          :columns="spotCheckColumns"
          :data-source="spotCheckData"
          class="components-table-demo-nested"
          bordered
          :pagination="false"
          style="margin-top:10px;"
        >
          <template slot="index" slot-scope="text,record,index">
            <span>{{index+1}}</span>
          </template>
          <template slot="inspectProject" slot-scope="text,record,index">
            <p-select
              v-model="record.inspectProject"
              placeholder="please select your zone"
              disabled
            >
              <p-select-option
                v-for="(item,index) in inspectProjectOptions"
                :key="index"
                :value="item.value"
              >{{item.name}}</p-select-option>
            </p-select>
          </template>

          <template slot="edit" slot-scope="text,record">
            <p-button type="link" @click="spotCheckEdit(record)">编辑</p-button>
          </template>
          <template slot="delete" slot-scope="text,record">
            <p-popconfirm
              title="是否删除当前数据"
              ok-text="Yes"
              cancel-text="No"
              @confirm="confirm(record)"
              @cancel="cancel"
            >
              <a href="#">删除</a>
            </p-popconfirm>
          </template>
        </p-table>
        <p-button style="margin-top:10px" @click="spotCheckAdd">新增明细</p-button>
      </p-drawer>
      <!-- 侧边弹出结束 -->

      <p-page-header
              style="border: 1px solid rgb(235, 237, 240)"
              title="入库检操作"
      >
        <template slot="extra">

          <p-button key="1" type="primary" @click="saveDataBtn">
            保存
          </p-button>

          <p-popconfirm
                  title="确定要提交吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="submitData"
                  @cancel="cancel"
          >
            <p-button type="primary">提交</p-button>
          </p-popconfirm>

          <p-button key="1" type="danger" @click="">
            产品锁定
          </p-button>

          <p-button key="1" type="danger" @click="">
            异常记录
          </p-button>

          <p-button @click="backToIndex">取消</p-button>
        </template>
      </p-page-header>


      <h4 class="title">基础信息</h4>
      <p-form-model
        ref="baseInfoData"
        :model="baseInfoData"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <p-row :gutter="24">
          <p-col :span="8">
            <p-form-model-item ref="inspectBillno" label="送检单号" prop="inspectBillno">
              <p-input
                      readOnly
                v-model="baseInfoData.inspectBillno"
                @blur="
          () => {
            $refs.inspectBillno.onFieldBlur();
          }
        "
              />
            </p-form-model-item>
          </p-col>
          <p-col :span="8">
            <p-form-model-item ref="productionno" label="生产工单" prop="productionno">
              <p-input
                      readOnly
                      v-model="baseInfoData.productionno"
                      @blur="
          () => {
            $refs.productionno.onFieldBlur();
          }
        "
              />
            </p-form-model-item>
          </p-col>
          <p-col :span="8">
            <p-form-model-item ref="processbillno" label="工序工单" prop="processbillno">
              <p-input
                      readOnly
                v-model="baseInfoData.processbillno"
                @blur="
          () => {
            $refs.processbillno.onFieldBlur();
          }
        "
              />
            </p-form-model-item>
          </p-col>
          <p-col :span="8">
            <p-form-model-item ref="mcode" label="产品编号" prop="mcode">
              <p-input
                      readOnly
                v-model="baseInfoData.mcode"
                @blur="
          () => {
            $refs.mcode.onFieldBlur();
          }
        "
              />
            </p-form-model-item>
          </p-col>
          <p-col :span="8">
            <p-form-model-item ref="mname" label="产品名称" prop="mname">
              <p-input
                      readOnly
                v-model="baseInfoData.mname"
                @blur="
          () => {
            $refs.mname.onFieldBlur();
          }
        "
              />
            </p-form-model-item>
          </p-col>

          <p-col :span="8">
            <p-form-model-item ref="pnSendNumber" label="送检数量" prop="pnSendNumber">
              <p-input
                      readOnly
                      v-model="baseInfoData.sendInspectNumber"
                      @blur="
          () => {
            $refs.pnSendNumber.onFieldBlur();
          }
        "
              />
            </p-form-model-item>
          </p-col>

          <p-col :span="8">
            <p-form-model-item ref="simpleMethod" label="抽检方式" prop="simpleMethod">
              <p-input
                      v-if="baseInfoData.simpleMethod==1"
                      readOnly
                      v-model="baseInfoData.simpleMethodText"
              />
              <p-input
                      v-else
                      readOnly
                      v-model="baseInfoData.aqlSimpleStandardName"
              />
            </p-form-model-item>
          </p-col>
          <p-col :span="8">
            <p-form-model-item ref="simpleQty" label="抽检数量" prop="simpleQty">
              <p-input
                      readOnly
                      v-model="baseInfoData.simpleQty"
                      @blur="
          () => {
            $refs.simpleQty.onFieldBlur();
          }
        "
              />
            </p-form-model-item>
          </p-col>

          <p-col :span="8">
            <p-form-model-item ref="sendInspecter" label="送检人" prop="sendInspecter">
              <p-input
                      readOnly
                      v-model="baseInfoData.sendInspecter"
                      @blur="
          () => {
            $refs.sendInspecter.onFieldBlur();
          }
        "
              />
            </p-form-model-item>
          </p-col>

          <p-col :span="8">
            <p-form-model-item ref="sendInspectTime" label="送检时间" prop="sendInspectTime">
              <p-input
                      readOnly
                      v-model="baseInfoData.sendInspectTime"
                      @blur="
          () => {
            $refs.sendTime.onFieldBlur();
          }
        "
              />
            </p-form-model-item>
          </p-col>


          <p-col :span="8">
            <p-form-model-item ref="inspectAmount" label="检验次数" prop="inspectAmount">
              <p-input
                      readOnly
                      v-model="baseInfoData.inspectAmount"
                      @blur="
          () => {
            $refs.inspectAmount.onFieldBlur();
          }
        "
              />
            </p-form-model-item>
          </p-col>



          <p-col :span="8">
            <p-form-model-item ref="inspecter" label="检验人" prop="inspecter">
              <p-input
                      readOnly
                      v-model="baseInfoData.inspecter"
                      @blur="
          () => {
            $refs.inspecter.onFieldBlur();
          }
        "
              />
            </p-form-model-item>
          </p-col>




          <p-col :span="8">
            <p-form-model-item ref="inspectTime" label="检验时间" prop="inspectTime">
              <p-input
                      readOnly
                v-model="baseInfoData.inspectTime"
                @blur="
          () => {
            $refs.inspectTime.onFieldBlur();
          }
        "
              />
            </p-form-model-item>
          </p-col>
          <!-- <p-col :span="8">
            <p-form-model-item ref="sn" label="SN" prop="sn">
              <p-input
                v-model="baseInfoData.sn"
                @blur="
          () => {
            $refs.sn.onFieldBlur();
          }
        "
              />
            </p-form-model-item>
          </p-col>-->
        </p-row>

        <p-row>
          <p-col :span="1"></p-col>
          <p-col :span="5">
            <p-tag>送检产品SN*</p-tag><a @click="openSendPDSNModal">查询</a>
          </p-col>
          <p-col :span="5">
            <p-tag>入库检作业指导书*</p-tag><a>查询</a>
          </p-col>
          <p-col :span="5">
            <p-tag>附件*</p-tag><a @click="openBasicInfoPhotoUpload">上传</a>
          </p-col>

        </p-row>
      </p-form-model>

      <p-page-header
              style="border: 1px solid rgb(235, 237, 240)"
              title="检验项目"
      >
        <template slot="extra">

          <p-button key="1" type="primary" @click="addCheckProjectBtn">
            新增行
          </p-button>


        </template>
      </p-page-header>

      <div>
        <p-modal :visible="addCPModalVisible" width="60vw" title="新增行-检验项目" @ok="sureAddCheckProject" @cancel="closeAddCPModal" okText="添加" cancelText="取消">
          <p-alert message="请勾选包含检验明细的检验项目" type="info" v-if="selectedType==1" show-icon />
          <p-alert message="满足条件，点击“添加”按钮插入" type="success" v-if="selectedType==2" show-icon />
          <p-alert message="该项没有对应的明细列表" type="warning" v-if="selectedType==3" show-icon />

          <h4 class="title"></h4>
          <p-table
                  :data-source="templateList"
                  :columns="templateListColumns"
                  :rowSelection="{ selectedRowKeys: selectedRowKeysArray, onChange: onSelectChange, type: 'radio' }"
          >
            <div
                    slot="filterDropdown"
                    slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
                    style="padding: 8px"
            >
              <p-input
                      v-ant-ref="c => (searchInput = c)"
                      :placeholder="`搜索 ${column.title}`"
                      :value="selectedKeys[0]"
                      style="width: 188px; margin-bottom: 8px; display: block;"
                      @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
                      @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
              />
              <p-button
                      type="primary"
                      icon="search"
                      size="small"
                      style="width: 90px; margin-right: 8px"
                      @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
              >
                搜索
              </p-button>
              <p-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
                重置
              </p-button>
            </div>
            <p-icon
                    slot="filterIcon"
                    slot-scope="filtered"
                    type="search"
                    :style="{ color: filtered ? '#108ee9' : undefined }"
            />
            <template slot="customRender" slot-scope="text, record, index, column">
      <span v-if="searchText && searchedColumn === column.dataIndex">
        <template
                v-for="(fragment, i) in text
            .toString()
            .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
        >
          <mark
                  v-if="fragment.toLowerCase() === searchText.toLowerCase()"
                  :key="i"
                  class="highlight"
          >{{ fragment }}</mark
          >
          <template v-else>{{ fragment }}</template>
        </template>
      </span>
              <template v-else>
                {{ text }}
              </template>
            </template>
          </p-table>

          <h4 class="title"></h4>
          <p-table
                  :data-source="templateListDetails"
                  :columns="templateListDetailsColumns"
          >

          </p-table>


        </p-modal>
      </div>


      <p-table
              :columns="modal1InspectionColumns"
              :data-source="baseInfoData.checkProjectList"
              class="components-table-demo-nested"
              bordered
              :expandIcon="expandIcon"
              style="margin-top:10px;"
      >


        <template slot="photoUrl" slot-scope="text,record">

          <p-button type="primary" icon="upload" :disabled="reviewVisible" @click="openPhUpBtn2(record)" >上传</p-button>
          <!-- <p-divider type="vertical" />
           <p-button type="primary" icon="download" @click="openPhDownBtn(record.key)">下载</p-button>-->
          <p-divider type="vertical" v-if="record.photoUrl&&record.photoUrl!=''"/>
          <p-button v-if="record.photoUrl&&record.photoUrl!=''" type="primary" icon="eye" @click="openPhReviewBtn2(record)">预览</p-button>
        </template>

        <template slot="operation" slot-scope="text,record">
          <p-popconfirm
                  title="确定要删除此项？"
                  ok-text="删除"
                  cancel-text="取消"
                  @confirm="deleteCheckProject(record)"
          >
            <a href="#">删除</a>
          </p-popconfirm>
        </template>


        <p-table
                slot="expandedRowRender"
                slot-scope="text"
                :columns="modal1InspectionInnerColumns"
                :data-source="text.detailList"
                :pagination="false"

                bordered
        >



          <template slot="measuredValue" slot-scope="text,record">

            <p-select v-if="record.valueType==2" v-model="record.measuredValue" style="width: 100px;" placeholder="please select your zone" @change="measuredValueChange">
              <p-select-option
                      v-for="(item,index) in passNgOptions"
                      :key="index"
                      :value="item.value"
              >{{item.name}}</p-select-option>
            </p-select>
            <p-input v-else type="number"  v-model="record.measuredValue "  style="width: 100px;" @change="measuredValueChange2"/>
          </template>





          <template slot="defectLevel" slot-scope="text,record">
            <p-select v-model="record.defectLevel" placeholder="please select your zone" >
              <p-select-option
                      v-for="(item,index) in defectLevelOptions"
                      :key="index"
                      :value="parseInt(item.value)"
              >{{item.title}}</p-select-option>
            </p-select>
          </template>




         <!-- <template slot="photoUrl" slot-scope="text,record">

            <p-button type="primary" icon="upload" :disabled="reviewVisible" @click="openPhUpBtn2(record)" >上传</p-button>
            &lt;!&ndash; <p-divider type="vertical" />
             <p-button type="primary" icon="download" @click="openPhDownBtn(record.key)">下载</p-button>&ndash;&gt;
            <p-divider type="vertical" v-if="record.photoUrl&&record.photoUrl!=''"/>
            <p-button v-if="record.photoUrl&&record.photoUrl!=''" type="primary" icon="eye" @click="openPhReviewBtn2(record)">预览</p-button>
          </template>
-->


        </p-table>

    <!--    <template slot="photoUrl" slot-scope="text">
          <p-button>{{text.photoUrl}}</p-button>
        </template>
-->


      </p-table>
      <p-modal v-model="phUpVisible2" title="图片上传" @ok="phUpSave2" okText="保存更改">
        <j-upload v-model="currentDetailPhObj" :trigger-change="true" :ismultiSelect="true"></j-upload>
      </p-modal>



      <div>
        <p-modal v-model="dPhVisible" title="图片预览(非图片文件无法预览-需下载)" :footer="null" :width="1000">
          <img :src="dPhUrl" class="myImg"/>
        </p-modal>
      </div>


      <h4 class="title">质量判定</h4>

      <p-form-model
        ref="processProcessingData"
        :label-col="{span:2}"
        :wrapper-col="{span:12}"
        :model="baseInfoData"
        :rules="rules"
        style="margin-top:12px;"
      >
        <p-row :gutter="24">
          <p-col :span="24">
            <p-form-model-item ref="inspectResult" label="检验结论" prop="inspectResult">


              <p-tag v-if="baseInfoData.inspectResult==1" color="green"><p-icon type="check-circle" />合格</p-tag>
              <p-tag v-else-if="baseInfoData.inspectResult==2" color="red"><p-icon type="close-circle" />不合格</p-tag>
            </p-form-model-item>
          </p-col>
          <p-col :span="24" v-if="baseInfoData.inspectResult==2">
            <p-form-model-item ref="releaseOrderNo" label="MRB放行单号" prop="releaseOrderNo" >
              <p-select v-model="baseInfoData.mrb"  allowClear>
                <div slot="dropdownRender">
                  <p-table
                    :columns="releaseOrderNoColumns"
                    :data-source="releaseOrderNoData"
                    :pagination="false"
                    :customRow="selectReleaseOrder"
                    bordered
                  >
                    <template slot="index" slot-scope="text,record,index">
                      <span>{{index+1}}</span>
                    </template>
                    <template slot="orderInfo" slot-scope="text,record">
                      <p-button type="link" @click.stop="checkReleaseOrderInfo(record)">{{text}}</p-button>
                    </template>
                  </p-table>
                </div>
              </p-select>
            </p-form-model-item>
          </p-col>
        </p-row>
      </p-form-model>

    </div>

    <p-modal v-model="sendPDSNVisible" title="送检产品SN" :footer="null" :width="1200">
      <p-table
              :columns="inspectionProductsColumns"
              :data-source="baseInfoData.proDetailsList"
              class="components-table-demo-nested"
              bordered
              style="margin-top:10px;"
      >

      </p-table>
    </p-modal>

  <!--  <p-modal v-model="basicInfoPhotoModalVisible" title="附件上传" @ok="saveBasicInfoPhoto" okText="保存更改" >-->
    <p-modal v-model="basicInfoPhotoModalVisible" title="附件上传" :footer="null" >
      <j-upload v-model="baseInfoData.photoUrl" :trigger-change="true" :ismultiSelect="true"></j-upload>
    </p-modal>



  </p-card>
</template>

<script>
  import {deleteAction, getAction, postAction, putAction} from "../../../api/manage";
  import JUpload from '@/components/jeecg/JUpload'

export default {
  name: "MesQcInfoOpe",
  props:['mqVisible','mqLoad','mqData'],
  components: {
    JUpload,
  },
  data() {
    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },

      //新增行弹出框
      addCPModalVisible:false,
      reviewVisible:false,
      basicInfoPhotoModalVisible:false,
      templateList:[],
      templateListDetails:[],
      selectedRowKeysArray:[],
      selectedRows:[],
      selectedType:1,
      currentSnPhKey:0,
      currentD:{},
      phUpVisible2:false,
      dPhVisible:false,
      currentDetailPhObj:'',
      dPhUrl:'',

      inspectionProductsColumns: [
        { title: "序号",
          dataIndex: "",
          key: "rowIndex",
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }, },
        { title: "线体", dataIndex: "linename", key: "linename" },
        {
          title: "生产工单",
          dataIndex: "productionno",
          key: "productionno",
        },
        { title: "工序工单", dataIndex: "processbillno", key: "processbillno" },
        { title: "产品编码", dataIndex: "mcode", key: "mcode" },
        { title: "产品名称", dataIndex: "mname", key: "mname" },
        { title: "栈板号/容器码", dataIndex: "palletNo", key: "palletNo" },
        { title: "SN/PN", dataIndex: "sn", key: "sn" },
        { title: "数量", dataIndex: "qty", key: "qty",scopedSlots: {customRender: "qty"} },
        { title: "状态", dataIndex: "status", key: "status",
          customRender: (text) => {
            if (!text) {
              return "";
            } else {
              return text==1?'未检':'已检';
            }
          },
        },
      ],
      inspectionProductsnData: [

      ],

      modal1InspectionColumns: [
        {
          title: "序号",
          dataIndex: "key",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
        },
        { title: "SN", dataIndex: "sample", key: "sample" },
        { title: "物料编码", dataIndex: "mcode", key: "mcode" },
        { title: "物料名称", dataIndex: "mname", key: "mname" },
       /* { title: "物料小类", dataIndex: "subcategory", key: "subcategory" },*/
        { title: "物料一级分类", dataIndex: "productOneType", key: "productOneType" },
        { title: "物料二级分类", dataIndex: "productTwoType", key: "productTwoType" },
        { title: "物料三级分类", dataIndex: "productThreeType", key: "productThreeType" },
        { title: "检验结果",
          dataIndex: "inspectResult",
          key: "inspectResult",
          customRender: (text) => {
            if (!text) {
              return "";
            } else {
              return text==1?'合格':'不合格';
            }
          },
        },
        {
          title: "图片",
          dataIndex: "photoUrl",
          key: "photoUrl",
          scopedSlots: { customRender: "photoUrl" },
        },

        {title:"操作",key:"id",dataIndex: 'id',scopedSlots: {customRender: "operation"}}
      ],

      modal1InspectionInnerColumns: [
        {
          title: "序号",
          dataIndex: "key",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },

        },
        { title: "检验项目", dataIndex: "inspectItem", key: "inspectItem" },
        {
          title: "检验标准",
          dataIndex: "inspectStandard",
          key: "inspectStandard",
        },
        {
          title: "值类型",
          dataIndex: "valueType",
          key: "valueType",
          customRender: (text) => {
            if (!text) {
              return "";
            } else {
              return  text==1?"计量型":"计数型";
            }
          },
        },
        { title: "标准值", dataIndex: "standardValue", key: "standardValue", scopedSlots: { customRender: "standardValue" }, },
        {
          title: "上限值",
          dataIndex: "upperValue",
          key: "upperValue",
          scopedSlots: { customRender: "upperValue" },
        },
        { title: "下限值", dataIndex: "downValue", key: "downValue" , scopedSlots: { customRender: "downValue" },},
        { title: "参数", dataIndex: "param", key: "param",scopedSlots: { customRender: "param" }, },
        {
          title: "实测值",
          dataIndex: "measuredValue",
          key: "measuredValue",
          scopedSlots: { customRender: "measuredValue" },
        },
        {
          title: "单项判定",
          dataIndex: "individualJudgment",
          key: "individualJudgment",
          customRender: (text) => {
            if (!text) {
              return "";
            } else {
              return  text==1?"PASS":"NG";
            }
          },
        },
        {
          title: "缺陷等级",
          dataIndex: "defectLevel",
          key: "defectLevel",
          scopedSlots: { customRender: "defectLevel" },
        },


      ],

      templateListColumns:[
        { title: "抽样样本",
          dataIndex: "sample",
          key: "sample",
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
                  record.sample
                          .toString()
                          .toLowerCase()
                          .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        { title: "物料编码", dataIndex: "mcode", key: "mcode" },
        { title: "物料名称", dataIndex: "mname", key: "mname" },
      ],
      templateListDetailsColumns:[
        { title: "检验项目", dataIndex: "inspectItem", key: "inspectItem" },
        { title: "检验标准", dataIndex: "inspectStandard", key: "inspectStandard" },
        { title: "值类型", dataIndex: "valueType", key: "valueType",
          customRender: (text) => {
            if (!text) {
              return "";
            } else {
              return text==1?'计量型':'计数型';
            }
          },
        },
        { title: "标准值", dataIndex: "standardValue", key: "standardValue" },
        { title: "上限值", dataIndex: "upperValue", key: "upperValue" },
        { title: "下限值", dataIndex: "downValue", key: "downValue" },
      ],


      passNgOptions:[
        {
          name: "PASS",
          value: "PASS",
        },
        {
          name: "NG",
          value: "NG",
        },
      ],




      baseInfoData: {
        //基础信息
        inspectBillno: "001", //送检单号
        processBillno: "", //工序工单
        mcode: "001", //产品编号
        mname: "", //产品名称
        processTwo: "", //二级工序
        linename: "", //线体
        sendTime: "", //送检时间
        simpleMethod: "", //抽样方式
        simpleQty: "3", //抽样数量
        inspecter: "", //检验人
        inspectTime: "", //检验时间
        // sn: "", //sn
        inspectResult: 1,
        releaseOrderNo: "", //整改情况
      },
      rules: {
        inspectBillno: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        processbillno: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        productionno: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        pnSendNumber: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        sendInspecter: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        inspectAmount: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        mcode: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        mname: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        processTwo: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        linename: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        sendInspectTime: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        simpleMethod: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        simpleQty: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        inspecter: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        inspectTime: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        inspectResult: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],

        // sn: [
        //   {
        //     required: true,
        //     message: "Please input Activity name",
        //     trigger: "blur",
        //   },
        // ],
      },
      //抽检SN明细
      spotCheckColumns: [
        {
          title: "序号",
          scopedSlots: { customRender: "index" },
        },
        { title: "SN", dataIndex: "sn", key: "sn" },
        {
          title: "检验项目",
          dataIndex: "inspectProject",
          key: "inspectProject",
          scopedSlots: { customRender: "inspectProject" },
        },
        { title: "图片", dataIndex: "photoUrl", key: "photoUrl" },
        { title: "备注", dataIndex: "remark", key: "remark" },
        {
          title: "编辑",
          dataIndex: "edit",
          key: "edit",
          scopedSlots: { customRender: "edit" },
        },
        {
          title: "删除",
          dataIndex: "delete",
          key: "delete",
          scopedSlots: { customRender: "delete" },
        },
      ],
      spotCheckData: [
        {
          key: 1,
          sn: "123456",
          inspectProject: 1,
          photoUrl: "",
          remark: "",
        },
        {
          key: 2,
          sn: "123456",
          inspectProject: 2,
          photoUrl: "",
          remark: "",
        },
      ],
      inspectProjectOptions: [
        { name: "空", value: 0 },
        { name: "包装", value: 1 },
        { name: "外观", value: 2 },
      ],
      currentRow: {},
      addRow: {},
      spotCheckModalVisible: false,
      spotCheckModalVisible2: false,
      spotCheckLabelCol: { span: 5 },
      spotCheckWrapperCol: { span: 18 },
      // 检验项目数据
      inspectionItemsColumns: [
        {
          title: "序号",
          dataIndex: "index",
          scopedSlots: { customRender: "index" },
        },
        { title: "线号/组件编号", dataIndex: "lineBillno", key: "lineBillno" },
        {
          title: "产品编码",
          dataIndex: "mcode",
          key: "mcode",
        },
        {
          title: "产品名称",
          dataIndex: "mname",
          key: "mname",
        },
        { title: "产品小类", dataIndex: "msmall", key: "msmall" },
        { title: "产品大类", dataIndex: "mbig", key: "mbig" },
        { title: "检验结果", dataIndex: "inspectResult", key: "inspectResult" },
        {
          title: "图片",
          dataIndex: "photoUrl",
          key: "photoUrl",
          scopedSlots: { customRender: "photoUrl" },
        },
      ],
      inspectionItemsData: [
        {
          key: 1,
          lineBillno: "请输入或者选择线号/组件编号（比如#23 #43）",
          mcode: "自动带出",
          mname: "自动带出",
          msmall: "自动带出",
          mbig: "自动带出",
          inspectResult: "根据检验项目自动判断是否合格",
          photoUrl: "详情",
        },
        {
          key: 2,
          lineBillno: "请输入或者选择线号/组件编号（比如#23 #43）",
          mcode: "自动带出",
          mname: "自动带出",
          msmall: "自动带出",
          mbig: "自动带出",
          inspectResult: "根据检验项目自动判断是否合格",
          photoUrl: "详情",
        },
      ],
      inspectionItemsInnerColumns: [
        {
          title: "序号",
          dataIndex: "index",
          scopedSlots: { customRender: "index" },
        },
        { title: "工站", dataIndex: "workStation", key: "workStation" },
        {
          title: "检验项目",
          dataIndex: "inspectProject",
          key: "inspectProject",
        },
        {
          title: "检验标准",
          dataIndex: "inpectStandard",
          key: "inpectStandard",
        },
        { title: "值类型", dataIndex: "valueType", key: "valueType" },
        { title: "检验手段", dataIndex: "inspectMethod", key: "inspectMethod" },
        { title: "标准值", dataIndex: "standardValue", key: "standardValue" },
        { title: "上限值", dataIndex: "upperValue", key: "upperValue" },
        { title: "下限值", dataIndex: "downValue", key: "downValue" },
        { title: "实测值", dataIndex: "measuredValue", key: "measuredValue" },
        {
          title: "单项判定",
          dataIndex: "individualJudgment",
          key: "individualJudgment",
          customRender: (text) => {
            if (!text) {
              return "";
            } else {
              return  text==1?"PASS":"NG";
            }
          },
        },
      ],
      inspectionItemsInnerData: [
        {
          key: 1,
          workStation: "线材预制",
          inspectProject: "L1",
          inpectStandard:
            "线缆型号、拨线方式、拨线长度符合SOP要求，屏蔽层及线缆馈芯无刀痕等损伤",
          valueType: "计量型",
          inspectMethod: "目测",
          standardValue: "175",
          upperValue: "+0.3",
          downValue: "-.2",
          measuredValue: "175",
          individualJudgment: "Pass",
        },
        {
          key: 2,
          workStation: "线材预制",
          inspectProject: "L1",
          inpectStandard:
            "线缆型号、拨线方式、拨线长度符合SOP要求，屏蔽层及线缆馈芯无刀痕等损伤",
          valueType: "计量型",
          inspectMethod: "目测",
          standardValue: "175",
          upperValue: "+0.3",
          downValue: "-.2",
          measuredValue: "175",
          individualJudgment: "Pass",
        },
      ],
      measuredValueOptions: [
        {
          name: "pass",
          value: 1,
        },
        {
          name: "NG",
          value: 0,
        },
      ],
      sendPDSNVisible:false,
      defectLevelOptions: [

      ],
      inspectResultOptions: [
        { name: "合格", value: 1 },
        { name: "不合格", value: 2 },

      ],
      drawerVisible: false,
      // MRB放行单号
      releaseOrderNoColumns: [
        {
          title: "序号",
          dataIndex: "index",
          scopedSlots: { customRender: "index" },
        },
        { title: "MRB放行单号", dataIndex: "orderNo", key: "orderNo" },
        {
          title: "MRB报告",
          dataIndex: "orderInfo",
          key: "orderInfo",
          scopedSlots: { customRender: "orderInfo" },
        },
      ],
      releaseOrderNoData: [

      ],
      selectReleaseOrder: (record) => ({
        // 事件
        on: {
          click: () => {
            console.log(record, "record");
            this.baseInfoData.mrb = record.orderNo;
          },
        },
      }),
    };
  },
  computed: {},

  created() {
    this.initDefectLevelOptions();
    this.initInspectMethodList();
    this.mqListener();},

  methods: {
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm();
      this.searchText = selectedKeys[0];
      this.searchedColumn = dataIndex;
      this.resetSelectedNewLine();
    },
    handleReset(clearFilters) {
      clearFilters();
      this.searchText = '';
      this.resetSelectedNewLine();
    },


    resetSelectedNewLine(){
      this.selectedRowKeysArray = [];
      this.selectedRows = [];
      this.templateListDetails = [];
      this.selectedType = 1;
    },
    mqListener(){
      console.log(this.mqVisible)
      console.log(this.mqLoad)
      console.log(this.mqData)
      this.initData(this.mqData);
    },
    backToIndex(){
      let mqData = this.mqData;
      this.$emit('update:mqVisible', 1);
      this.$emit('update:mqLoad', false);
      mqData.id = 0;
      this.$emit('update:mqData', mqData);
    },
    /**
     * 初始化RMB单号list
     */
    initReleaseOrderNoData(){
      let releaseOrderNoData = [
        {
          key: 1,
          orderNo: "HR-MRB20200520001",
          orderInfo: "详情",
        },
        {
          key: 2,
          orderNo: "HR-MRB20200520002",
          orderInfo: "详情",
        },
      ];

      this.releaseOrderNoData = releaseOrderNoData;
    },
    initInspectMethodList(){
      getAction('/basic-business/sys/dict/queryDictItemsByCode',{dictCode:'rc_inspect_method'}).then(res=>{
        if(res.success){
          this.inspectMethodList = res.data;
          this.inspectMethodMap = this.listToMap(this.inspectMethodList,'value');
        }
      })
    },

    initDefectLevelOptions(){
      getAction('/basic-business/sys/dict/queryDictItemsByCode',{dictCode:'mes_err_level'}).then(res=>{
        if(res.success){
          this.defectLevelOptions = res.data;
        }
      })
    },

    openSendPDSNModal(){
      this.sendPDSNVisible = true;
    },

    openBasicInfoPhotoUpload(){
      this.basicInfoPhotoModalVisible = true;
    },
    saveBasicInfoPhoto(){
      this.basicInfoPhotoModalVisible = false;
    },
    //封装listToMap
    listToMap(list,name){
      let map = {};
      for(let i in list){
        map[list[i][name]] = list[i];
      }
      return map;
    },
    /**
     * 数据初始化
     */
    initData(query) {

      if (!query.id) {
        this.$message.warning("请通过来入库检验清单选择单号进入！");
      } else {
        let id = query.id;
        getAction('/mes-quality/mesQcIntoWarehouseInspectTask/selectById/'+id).then(res=>{
          if(res.success){
            let data = res.data;
            if(data.checkProjectList.length>0){
              let key = 1;
              data.checkProjectList.forEach(item=>{
                item.key = key;


                if(item.detailList.length>0){
                  let sonKey = 1;
                  item.detailList.forEach(jtem=>{
                    jtem.key = sonKey;
                    jtem.fKey = key;
                    sonKey = sonKey + 1;
                  })
                }
                key= key +1;

              })
            }

            if(data.checkProjectList.length==0){

              data.inspectResult = 2;
            }

            data.inspecter= this.$store.state.user.name;


            console.log('this.inspectMethodMap:-------------')
            console.log(this.inspectMethodMap)
            console.log(this.inspectMethodMap[data.simpleMethod])
            data.simpleMethodText = data.simpleMethod?this.inspectMethodMap[data.simpleMethod]?this.inspectMethodMap[data.simpleMethod].title:'':'' ;
            this.baseInfoData = data;

            this.templateList = data.allCheckProjectList;



            /*this.initSampleTemplateList('aa');*/
            this.resetAllDataStatus();
            this.initReleaseOrderNoData();
          }else{
            this.$message.warning(res.msg);
          }
        })
      }
    },

    openPhUpBtn2(record){
      console.log(record)
      this.currentD = record;
      this.currentDetailPhObj = record.photoUrl;
      this.phUpVisible2 = true;

    },

    openPhReviewBtn2(record){
      this.dPhVisible = true;
      let obj = JSON.parse(record.photoUrl);
      this.dPhUrl = obj[0].filePath;
    },

    phUpSave2(){
      let data = {
        id:this.currentD.id,
        photoUrl:this.currentDetailPhObj
      }

      let r = this.currentD;
      postAction('/mes-quality/mesQcIntoWarehouseInspectTask/updateIncomeDetail',data).then(res=>{
        if(res.success){
          this.$message.success('操作成功!');
          this.phUpVisible2 = false;
          this.baseInfoData.checkProjectList[r.fKey-1].photoUrl = this.currentDetailPhObj;
        }else{
          this.$message.warning(res.msg)
        }
      })
    },
    openPhReviewBtn(key){
      let data = this.baseInfoData.mesQcTourinspSnDetailList[key-1];
      this.phReviewTitle = '['+data.sn+']'+'-'+'图片预览'
      let obj ;
      if(data.inspectProject&&data.inspectProject!=''){
        obj = JSON.parse(data.sonPhotoUrl);
      }else{
        obj = JSON.parse(data.photoUrl);
      }
      let phObj = [];
      if(obj&&obj.length>0){
        phObj = obj;
        let filePath = obj[0].filePath;
        filePath = filePath.substring(filePath.indexOf('=')+1)
        this.photoUrl = filePath;
      }else{
        this.photoUrl = '';
      }
      this.phObj = phObj;
      this.phIndex = 0;
      this.photoVisible=true;
      if(this.phObj.length==0){
        this.$message.warning('暂无图片,请上传！');
      }else{
        this.phReviewVisible = true;
      }
    },
    phUpSave(){
      let key = this.currentSnPhKey;
      let data = this.baseInfoData.mesQcTourinspSnDetailList[key-1];


      if(!data.inspectProject||data.inspectProject==''){
        data.photoUrl = this.currentPhObj;
        this.saveDataBtn();
      }else{
        let d = {
          id:data.id,
          inspectProject:data.inspectProject,
          photoUrl:this.currentPhObj
        }
        postAction('/mes-quality/mesQcTourInspectTask/updateTourSendProductDetail',d).then(res=>{
          if(res.success){
            this.$message.success('保存成功！');
            this.initData(this.mqData);
            this.phUpVisible = false;
          }else{
            this.$message.warning(res.msg)
          }
        })
      }
    },
    openPhUpBtn(key){
      this.currentSnPhKey = key;
      let data = this.baseInfoData.mesQcTourinspSnDetailList[key-1];
      if(data.inspectProject&&data.inspectProject!=''){
        this.currentPhObj = data.sonPhotoUrl;
      }else{
        this.currentPhObj = data.photoUrl;
      }

      this.phUpVisible = true;

      this.phUpTitle = '['+data.sn+']'+'-'+'图片上传'
    },

    /**
     * 删除检验项目
     */
    deleteCheckProject(e){
      let id = e.id;
      if(id){
        deleteAction('/mes-quality/mesQcIncomeBasicInfo/deleteMesQcIncomeCheckProject/'+id).then(res=>{
          if(res.success){
            this.$message.success("删除成功");
            this.initData(this.mqData);
          }else{
            this.$message.warning("删除失败");
          }
        })
      }else{

      }


    },

    /**
     * 保存
     */
    saveDataBtn(){
      let data = this.baseInfoData;
      putAction('/mes-quality/mesQcIntoWarehouseInspectTask/entity/operation',data).then(res=>{
        if(res.success){
          this.$message.success("保存成功");
          this.initData(this.mqData);
        }else{
          this.$message.warning("保存失败");
        }
      })
    },

    /**
     * 提交
     */
    submitData(){
      let data = this.baseInfoData;

      let flag = true;
      if(data.checkProjectList.length<data.simpleQty){
        flag = false;
        this.$message.error('检验项目数量不能小于抽检数量！')
      }
      putAction('/mes-quality/mesQcIntoWarehouseInspectTask/entityOperationSubmit',data).then(res=>{
        if(res.success){
          this.$message.success("提交成功！");
          this.backToIndex();
        }else{
          this.$message.warning(res.msg);
        }
      })
    },

    /**
     * 点击‘新增行’按钮
     */
    addCheckProjectBtn(){
      this.addCPModalVisible = true;
    },

    //结论下拉框change事件
    inspectResultSelectChange(value){
      this.baseInfoData.mrb = '';
    },



    /**
     * 检验项目单选框change事件
     */
    onSelectChange(selectedRowKeys, selectedRows){
      this.selectedRowKeysArray = selectedRowKeys;
      this.selectedRows = selectedRows;
      this.templateListDetails = selectedRows[0].detailList;
      if(this.templateListDetails.length>0){
        this.selectedType=2
      }else{
        this.selectedType=3
      }
    },


    /**
     *加载检验项目列表
     */
    initSampleTemplateList(sendBillno){

      getAction('/mes-quality/mesQcIncomeBasicInfo/querySampleTemplateList/'+ sendBillno).then(res=>{

        if (res.success) {
          let data = res.data;
          this.templateList = data;
        } else {
          this.$message.warning(res.msg);
        }
      })
    },


    /**
     * 确定添加
     */
    sureAddCheckProject(){
      let data = this.selectedRows[0];
      data.basicInfoId = this.baseInfoData.id;
      putAction('/mes-quality/mesQcIncomeBasicInfo/addCheckProjectList/rq',data).then(res=>{
        if(res.success){
          this.$message.success("新增成功！");
          this.resetRadioSelect();
          this.addCPModalVisible = false;
          this.initData(this.mqData);
        }else{
          this.$message.warning(res.msg);
        }
      })
    },
    /**
     * 取消-关闭modal
     */
    closeAddCPModal(){
      this.resetRadioSelect();
      this.addCPModalVisible = false;
    },

    /**
     * 重设radio
     */
    resetRadioSelect(){
      this.selectedRowKeysArray = [];
      this.selectedRows = [];
      this.templateListDetails = [];
      this.selectedType = 1;
    },

    /**
     * 展开图标
     * @param props
     * @returns {string|*}
     */
    expandIcon(props){
      if(props.record.detailList&&props.record.detailList.length>0){

        if (props.expanded) {
          return <p-icon type='minus-square' onClick={e => {props.onExpand(props.record, e);}}/>;
        }else{
          return <p-icon type='plus-square' onClick={e => {props.onExpand(props.record, e);}}/>;
        }

      }else{
        return "";
      }
    },


    measuredValueChange(value){
      this.resetAllDataStatus();
    },
    measuredValueChange2(value){
      this.resetAllDataStatus();
    },


    //根据第三层表的实测值更改联动二层表一层表的数据
    resetAllDataStatus(){
      let basicFlag = true;
      let firstInspectResult =  this.baseInfoData.inspectResult;
      this.baseInfoData.checkProjectList.forEach(item=>{
        let flag = true;
        let hasChild = false;
        item.detailList.forEach(item2=>{
          hasChild = true;

          if(!item2.valueType||item2.valueType==""){
            item2.individualJudgment = 2;
          }else{
            if(item2.valueType==2){
              item2.individualJudgment = item2.measuredValue=="PASS"?1:2;
            }else{
              /*if(item2.measuredValue>=item2.downValue&&item2.measuredValue<=item2.upperValue){
                item2.individualJudgment = 1;
              }else{
                item2.individualJudgment = 2;
              }*/

              let downValue = 0;
              let upperValue = 0;

              let measuredValue = parseFloat(item2.measuredValue);

              if((item2.downValue&&item2.downValue!='')&&(item2.upperValue&&item2.upperValue!='')){
                downValue = parseFloat(item2.downValue);
                upperValue = parseFloat(item2.upperValue);
                if(measuredValue>=downValue&&measuredValue<=upperValue){
                  item2.individualJudgment =1
                }else{
                  item2.individualJudgment =2

                }
              }else if((!item2.downValue||item2.downValue=='')&&(item2.upperValue&&item2.upperValue!='')){
                upperValue = parseFloat(item2.upperValue);
                if(measuredValue<=upperValue){
                  item2.individualJudgment =1
                }else{
                  item2.individualJudgment =2

                }
              }else if((item2.downValue&&item2.downValue!='')&&(item2.upperValue||item2.upperValue!='')){
                downValue  = parseFloat(item2.downValue);
                if(measuredValue>=downValue){
                  item2.individualJudgment =1
                }else{
                  item2.individualJudgment =2

                }
              }else{
                if(measuredValue>=downValue&&measuredValue<=upperValue){
                  item2.individualJudgment =1
                }else{
                  item2.individualJudgment =2

                }
              }
            }
          }


          if(!item2.individualJudgment||item2.individualJudgment==2||item2.individualJudgment==""){
            basicFlag = false;
            flag = false;
          }
        })

        if(hasChild){
          if(flag){
            item.inspectResult = 1;
          }else{
            item.inspectResult = 2;
          }
        }


      })
      if(basicFlag){
        this.baseInfoData.inspectResult = 1;
      }else{
        this.baseInfoData.inspectResult = 2;
      }

      if(this.baseInfoData.checkProjectList.length==0){
        this.baseInfoData.inspectResult = 2;
      }

      if(firstInspectResult!=this.baseInfoData.inspectResult){
        this.baseInfoData.mrb='';
      }
    },


    spotCheckEdit(record) {
      // console.log("spotCheckEdit", record);
      this.spotCheckModalVisible = true;
      this.currentRow = JSON.parse(JSON.stringify(record));
    },
    confirm(record) {
      //删除抽检SN明细
      console.log(record);
      this.spotCheckData.forEach((item, index, arr) => {
        if (item.key == record.key) {
          arr.splice(index, 1);
          console.log(arr);
        }
      });
      this.$message.success("删除成功");
    },
    cancel(record) {
      this.$message.error("取消删除当前数据");
    },
    spotCheckDelete(record) {
      // console.log("spotCheckDelete", scope);
    },
    modalOk() {
      this.spotCheckData.forEach((item, index, arr) => {
        if (item.key == this.currentRow.key) {
          console.log("currentRow", this.currentRow, item);
          this.spotCheckData.splice(
            index,
            1,
            (item = JSON.parse(JSON.stringify(this.currentRow)))
          );
        }
      });

      this.spotCheckModalVisible = false;
    },
    //新增明细
    spotCheckAdd() {
      this.spotCheckModalVisible2 = true;
      let key = 0;
      this.spotCheckData.forEach((item) => {
        if (item.key > key) {
          key = item.key;
        }
      });
      this.addRow = {
        key: key + 1,
        sn: "",
        inspectProject: 0,
        photoUrl: "",
        remark: "",
      };
    },
    addModalOk() {
      this.spotCheckData.push(JSON.parse(JSON.stringify(this.addRow)));
      this.spotCheckModalVisible2 = false;
    },

    // 侧边弹出
    afterVisibleChange(val) {
      // console.log("visible", val);
    },
    showDrawer() {
      this.drawerVisible = true;
    },
    onClose() {
      this.drawerVisible = false;
    },
    // 查看MRB报告
    checkReleaseOrderInfo(record) {
      console.log("点击了我", record);

    },
  },
};
</script>
<style scoped>
@import "~@assets/less/common.less";
.title {
  padding: 8px 12px;
  background: #fafafa;
}
.title:not(:first-child) {
  margin-top: 10px;
}
/deep/ .poros-form {
  margin-top: 15px;
}
/deep/ .poros-table-body {
  overflow-x: auto !important;
}
/deep/ .poros-col {
  min-height: 54px;
}
/deep/ .poros-table thead th {
  height: 44px;
}
.highlight {
  background-color: rgb(255, 192, 105);
  padding: 0px;
}
</style>
